<template>
  <div class="suggest_container">
    <van-cell
      v-for="(item, index) in suggestionRegStr"
      :key="index"
      :center="true"
      @click="suggestionClick(index)"
    >
      <template #icon>
        <van-icon name="search" class="search=icon" />
      </template>
      <template #title>
        <div v-html="item"></div>
      </template>
    </van-cell>
  </div>
  <!-- <van-icon name="search" /> -->
</template>

<script>
// 引入防抖函数
import debounce from '@/untils/debounce.js'
export default {
  name: 'SearchSuggestion',
  props: ['searchValue', 'suggestionValues'],
  data () {
    return {
      suggestionLists: [],
      suggestionRegStr: []
    }
  },
  watch: {
    // 该回调将会在侦听开始之后被立即调用
    searchValue: {
      handler: function (newValue, oldValue) {
        const that = this
        debounce(function () {
          that.$emit('searchSuggestionValueChange', newValue)
        }, 500)
      },
      immediate: false
    },
    suggestionValues (lists) {
      this.suggestionRegStr.length = 0
      this.suggestionLists = lists
      const reg = new RegExp(this.searchValue, 'gi')
      this.suggestionLists.forEach(item => {
        const res = item.replace(reg, function (val) {
          return `<span class="line_height">${val}</span>`
        })
        this.suggestionRegStr.push(res)
      })
    }
  },
  methods: {
    // 搜索建议里的单元格点击事件
    suggestionClick (index) {
      this.$emit('suggestionClick', this.suggestionValues[index])
    }
  }
}
</script>

<style lang="less" scoped>
.suggest_container {
  /deep/.line_height {
    color: #58a9fb;
  }
}
</style>
